package com.madzone.gae.filem.model;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;

import com.google.appengine.api.datastore.Text;
import com.madzone.wiki.gae.ds.model.PMF;

@PersistenceCapable
public class TextFile extends File<Text> {
	
	@Persistent
	private Text content;
	
	public TextFile(String fileName, byte[] content) {
		super(fileName);
		setContentBytes(content);
	}
	
	public TextFile(String fileName, char[] content) {
		super(fileName);
		setContentChars(content);
	}
	
	public TextFile(String fileName, String content) {
		super(fileName);
		setContentString(content);
	}
	
	public TextFile() {
	}
	
	public Text getContent() {
		return content;
	}

	public void setContent(Text content) {
		this.content = content;
	}

	@Override
	public byte[] getContentBytes() {
		Text content = getContent();
		if (content != null) {
			return content.getValue().getBytes();
		}
		return null;
	}

	@Override
	public void setContentBytes(byte[] contentBytes) {
		Text content = new Text(new String(contentBytes));
		setContent(content);
	}
	
	public void setContentChars(char[] contentChars) {
		Text content = new Text(new String(contentChars));
		setContent(content);
	}
	
	public String getContentString() {
		Text content = getContent();
		if (content != null) {
			return content.getValue();
		}
		return null;
	}

	public void setContentString(String contentString) {
		Text content = new Text(contentString);
		setContent(content);
	}
	
	public static File getByName(String fileName) {
		String query = "select from " + TextFile.class.getName() + " where fileName == '" + fileName +"'";
		PersistenceManager pm = PMF.getPM();
		try {
			List<File> files = (List<File>) pm.newQuery(query).execute();
			if (files.isEmpty()) {
				return null;
			}
			return files.get(0);
		} finally {
			//pm.close();
		}
	}

}
